<?php
// ************************************************************************
// created on 28/03/2003, created by S.Gnanavel
// Purpose:
//        This class contains functions to display different html
//        interfaces.
//        It also contains functions for validating the value entered
//        for that field.
// ************************************************************************

class cForm
        {
        // *********************************************************
        // Variable Declaration
        // *********************************************************
        var $form_label;
        var $errors=array();
        var $validations=array();

        function cForm()
            {
            $form_locale=new cLocale("form_php.inc",$_SESSION["guser_preferences"]["language"]);
                }

        // ************************************************************************
        // created on 28/04/2003, created by S.Gnanavel
        // Purpose:
        //        This function displays the given string as label.
        // ************************************************************************

        // functions to display the values in the form
        function displayLabel($label1)
                {
                $this->form_label=$label1;
                echo "<b>$this->form_label </b>";
                }

        // functions to generate the html interfaces
        function generateInputTag($type,$properties="",$event="",$link="")
                {
                $input_code="<input class=\"forminput\" type=\"$type\" ";
                if ($properties)
                        {
                        foreach($properties as $key=>$value)
                                $input_code.=$key."="."\"$value\" ";
                        }
                if($type=="submit")
                        $input_code.=" onSubmit=\"blur()\"";

		if($value=="Save" || $value=="Update") 
			{
// 			echo $value;
			$input_code.="OnClick='return confirm(\"C o n f i r m ?\")'";
			}
		if($value=="Merge Stock" || $value=="submit")
			{
// 			echo $value;
			$input_code.="OnClick='return confirm(\"C o n f i r m ?\")'";
			}
                $input_code.=" $event>";
                if($link)
                     {
                     $input_code.=" $link";
                     }
                $name=$properties[name];
                if ($this->errors[$name])
                           $input_code.=$this->errors[$name];
                return $input_code;
                }

        /*////////////////////////////////////////////////////////////////////////////
        //
        //        generateSelectMenu()
        //
        //        arguments - 5
        //                $name                 - name of the select menu
        //                $default         - default value to be restored in the select menu
        //                $arrays                - array of values to be displayed in the select menu
        //                $event                - javascript events for the select menu
        //                $size                - no of elements to be displayed in the select menu on
        //                                          multiple selection is set.
        //
        //        action
        //                displays the given array of values in the select menu with default
        //                values as selected with multiple selection if set.
        //
        //        returns
        //                code for select tag
        //
        //        created on 28.04.2003 by S.Gnanavel
        //        Last Modified on 05.04.2003 by R.Lakshmi Narayanan
w        //
        ////////////////////////////////////////////////////////////////////////////*/
        function generateSelectMenu($name, $default, $arrays=array(),$default_name="",$size="",$restore_default=false,$event="", $width_css_class="")
                {
                if($size)
                        $multiple="size=\"$size\" multiple";
                $select_code="<select class=\"$width_css_class\" name=\"$name\" $multiple $event>";
                if ($default=="" || $restore_default==true)
                        {
                        if(!$default_name)
                                $default_name="--Select--";
                        if ($default=="" || $default[0]=="")
                                $selected="selected";
                        $select_code.="<option value=\"\" $selected>$default_name</option>";
                        }
                if($arrays)
                        {
                        for($i=0;$i< count($arrays);$i++)
                                $names[]=array_values($arrays[$i]);

                        foreach($names as $key=>$value)
                                {
                                $value_array[]=$value[0];
                                if($value[1])
                                        $name_array[]=$value[1];
                                else
                                        $name_array[]=$value[0];
                                }


                        // if multiple values are given as default show them as selected
                        if($multiple && $default)
                                {
                                for($i=0;$i< count($name_array);$i++)
                                        {
                                        $select_code.="<option value=\"$value_array[$i]\"";
                                        foreach($default as $default_value)
                                                {
                                                if($value_array[$i]==$default_value)
                                                        $select_code.=" selected ";
                                                }
                                        $select_code.="> $name_array[$i] </option>";
                                        }
                                }
                        else // show items in the select menu and show the default value if given
                                {
                                for($i=0;$i< count($name_array);$i++)
                                        {
                                        if ($value_array[$i]==$default)
                                                $select_code.="<option value=\"$value_array[$i]\" selected> $name_array[$i] </option>";
                                        else
                                                $select_code.="<option value=\"$value_array[$i]\"> $name_array[$i] </option>";
                                        }
                                }
                        }
                $select_code.="</select>";
                if ($this->errors[$name])
                        $select_code.=$this->errors[$name];
                return $select_code;
                }

        function trimValues(&$form)
                {
                //Removes any leading white spaces.
                if($form)
                        {
                        while(list($key,$value) = each($form))
                                $form[$key]=trim($value);
                        }
                }

        // functions for validating the form values

        // ************************************************************************
        // created on 28/04/2003, created by S.Gnanavel
        // Purpose:
        //        This function checks whether the given email address
        //        is valid or not. If valid it returns true else false.
        // ************************************************************************
        function checkEmail($email_address)
                {
                // Remove the leading white spaces
                $string = trim($email_address);
                // check email is valid or not
                $ret = ereg(    '^([a-z0-9_]|\\-|\\.)+'.
                                '@'.
                                '(([a-z0-9_]|\\-)+\\.)+'.
                                '[a-z]{2,4}$',
                                $email_address);
                return($ret);
                }

        function checkPrice($price)
                {
                if(strcmp($price,0)==0)
                        {
                        return true;
                        }
                else
                        {
                        return is_numeric($price);
                        }
                }

        function checkZero($value)
                {
                return ereg('^[-|+]{0,1}0{0,}[.]{0,}[0]{0,}$',$value);
                }
                
        function checkInt($value)
                {
                return ereg('^[-|+]{0,}[0-9]{0,}$',$value);
                }
        
        function checkNegative($value)
                {
                return ereg('^-[0-9]{0,}[.]{0,}[0-9]{0,}$',$value);
                }

        // ************************************************************************
        // created on 28/04/2003, created by S.Gnanavel
        // Purpose:
        //        This function checks whether the given date is valid date or not.
        //        If the date is valid then it returns true else it
        //        returns 0 (i.e; false).
        //        It returns false if the year is less than 1990
        //        or greater than 2020
        //        It uses "explode" and "list" functions of the php
        //        inorder to get the date, month and year portion
        //        in different variables, which is passed as arguments
        //        for "checkdate" php function which validates the date
        // ************************************************************************
        function checkValidDate($given_date,$format="dd/mm/yyyy")
                {
                switch ($format)
                        {
                        case "dd/mm/yyyy":
                                list ($day, $month, $year) = explode ("/", $given_date);
                                break;
                        case "mm/dd/yyyy":
                                list ($month, $day, $year) = explode ("/", $given_date);
                                break;
                        }
                if ($year>1990 && $year<2099)
                         {
                        return (checkdate($month, $day, $year));
                        }
                else
                        {
                        return false;
                        }
                }

        function checkPreferredValidDate($given_date,$format="dd/mm/yyyy")
                {
                
                switch ($format)
                        {
                        case "dd/mm/yyyy":
                                list ($day, $month, $year) = explode ("/", $given_date);
                                break;
                        case "mm/dd/yyyy":
                                list ($month, $day, $year) = explode ("/", $given_date);
                                break;
                        }
                list($from_date,$to_date)=explode("~",$_SESSION["guser_preferences"]["valid_date_range"]);
                $g_date="$year-$month-$day";
                if($g_date >= $from_date && $g_date <= $to_date)
                         {
                        return (checkdate($month, $day, $year));
                        }
                else
                        {
                        return false;
                        }
                }
                
                function checkValidTime($given_time)
                        {
                        $valid_date = ereg('[0-9][0-9]:[0-9][0-9]',        $given_time);

                        if($valid_date)
                                {
                                list($hour,$minute)=explode(":",$given_time);
                                if ($hour>0 && $hour<=12 && $minute>=0 && $minute<=59)
                                        return true;
                                }
                        else
                                return false;
                        }

        // **********************************************************
        // created on 28/04/2003, created by S.Gnanavel
        // Purpose:
        //        This function validates the given associative array
        //        of values for validations specified for each value.
        //        For every value in the array the validations to be
        //        done for that value is carried out.
        //        This function can validate the given value for
        //        # is empty (uses php function: empty)
        //        # is numeric (uses php function: is_numeric)
        //        # is email (uses user_defined function: checkEmail)
        //        # is date (uses user_defined function: checkValidDate)
        //        In the process of validation, if one validation fails
        //        then the error is assigned for that value and
        //        validation for next value begins.
        // **********************************************************
        function validate(&$values)
                {
                global $form_locale;
                $this->errors=array();
                foreach($this->validations as $name=>$validateFor)
                        {
                        $val=$values[$name];
                        if (isset($validateFor[isEmpty]) && $val=="")
                                {
                                if (!empty($validateFor[isEmpty]))
                                        $errors=$validateFor[isEmpty];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isEmpty"]." ".$this->form_label;
                                }
                        elseif (isset($validateFor[isPrice]) && $this->checkPrice($val)==false)
                                {
                                if (!empty($validateFor[isPrice]))
                                        $errors=$validateFor[isPrice];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isPrice"];
                                }
                        elseif (isset($validateFor[isNegative]) && $this->checkNegative($val)==true)
                                {
                                if (!empty($validateFor[isNegative]))
                                        $errors=$validateFor[isNegative];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isNegative"];
                                }
                        elseif (isset($validateFor[isZero]) && $this->checkZero($val)==true)
                                {
                                if (!empty($validateFor[isZero]))
                                        $errors=$validateFor[isZero];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isZero"];
                                }
                        elseif ( isset($validateFor[isNumeric]) && !is_numeric($val))
                                {
                                if (!empty($validateFor[isNumeric]))
                                        $errors=$validateFor[isNumeric];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isNumeric"];
                                }
                        elseif (isset($validateFor[isInt]) && $this->checkInt($val) == false)
                                {
                                if (!empty($validateFor[isInt]))
                                        $errors=$validateFor[isInt];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isInt"];
                                }
                        elseif (isset($validateFor[isEmail]) && !$this->checkEmail($val))
                                {
                                if (!empty($validateFor[isEmail]))
                                        $errors=$validateFor[isEmail];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isEmail"];
                                }
                        elseif (isset($validateFor[isDate]) && !$this->checkValidDate($val))
                                {
                                if (!empty($validateFor[isDate]))
                                        $errors=$validateFor[isDate];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isDate"];
                                }
                        elseif (isset($validateFor[isPreferredDate]) && !$this->checkPreferredValidDate($val))
                                {
                                if (!empty($validateFor[isDate]))
                                        $errors=$validateFor[isDate];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isDate"];
                                }
                        elseif (isset($validateFor[isTime]) && !$this->checkValidTime($val))
                                {
                                if (!empty($validateFor[isTime]))
                                        $errors=$validateFor[isTime];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["isTime"];
                                }
                        elseif (isset($validateFor[checkPassword]) && !$this->checkLength($val, 5, 15))
                                {
                                if (!empty($validateFor[checkPassword]))
                                        $errors=$validateFor[checkPassword];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["Password_Length"];
                                }
                        elseif (isset($validateFor[checkLogin]) && !$this->checkLength($val, 5, 20))
                                {
                                if (!empty($validateFor[checkLogin]))
                                        $errors=$validateFor[checkLogin];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["Login_Length"];

                                }
                        elseif (isset($validateFor[checkPassword]) && !$this->checkAllowableCharacters($val))
                                {
                                if (!empty($validateFor[checkPassword]))
                                        $errors=$validateFor[checkPassword];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["Password_Char"];
                                }
                        elseif (isset($validateFor[checkLogin]) && !$this->checkAllowableCharacters($val))
                                {
                                if (!empty($validateFor[checkLogin]))
                                        $errors=$validateFor[checkLogin];
                                else
                                        $errors=$form_locale->ERRORS["form_php.inc"]["Login_Char"];
                                }
                        else
                                $errors="";
                        if ($errors)
                                $this->errors[$name]="<div class=\"error\">".$errors."</div>";
                        }
                }

        function getEmptyFieldErrors($form)
                {
                global $form_locale;
                while(list ($key,$value) = each ($form))
                        {
                        if ($value == "0" || trim($value) == "")
                                {
                                $new_key=$key;
                                while(strchr($new_key,"_"))
                                        $new_key=substr_replace($new_key," ",strpos($new_key,"_"),1);
                                $errors[$key] = "<div class=\"error\">".$form_locale->ERRORS["form_php.inc"]["isEmpty"] ." ". ucwords($new_key)."</div>";
                                }
                        else
                                unset($errors[$key]);
                        }
                return $errors;
                }

        function getNumericFieldErrors($form)
                {
                global $form_locale;
                foreach($form as $key => $value)
                        {
                        if (!is_numeric($value))
                                $errors[$key] = "<div class=\"error\">".$form_locale->ERRORS["form_php.inc"]["isNumeric"]."</div>";
                        else
                                unset($errors[$key]);
                        }
                return $errors;
                }

        function checkLength($string, $min, $max)
                {
                if (strlen($string)>=$min && strlen($string)<=$max)
                        return true;
                else
                        return false;
                }

        function checkAllowableCharacters($string)
                {
                $allowable_characters ='abcdefghefghijklmnopqrstuvwxyz0123456789_';

                for($i=0;$i<strlen($string);$i++)
                        {
                        if(!strchr($allowable_characters,$string[$i]))
                                return false;
                        }
                return true;
                }

        }

function getEditDate($given_date)
        {
        // convert the date string  to array.
        $date_array=explode('-', $given_date);
        //  Calculate time stamp.
        $stamp=mktime(0,0,0,$date_array[1], $date_array[2], $date_array[0]);
        // retrieves the date from the timestamp.
        return (date ("d/m/Y", $stamp));
        }

$form_locale=new cLocale("form_php.inc",$_SESSION["guser_preferences"]["language"]);
function displayCustomReportConstraint($sort_by,$given_constraint_array, $sort_order="")
        {
        global $form,$form_locale;
        echo "<br><form name=\"custom_report_constraint\" method=\"post\" action=\"$PHP_SELF\">";
        echo "<table align=\"left\" border=\"0\">";
                echo "<tr>";
                        echo "<td>";
                                $form->displayLabel($form_locale->LABEL["form_php.inc"]["Sort_By"]);
                                $i=0;
                                foreach($given_constraint_array as $name => $value)
                                        {
                                        $new_constraint_array[$i]["value"]=$value;
                                        $new_constraint_array[$i]["name"]=$name;
                                        $i++;
                                        }
                        echo $form->generateSelectMenu("sort_by",$sort_by,$new_constraint_array);
                        $sort_order = (!$sort_order)?"ascending":$sort_order;
                        $ascending_sort_order_selected=($sort_order=="ascending")?"checked":"";
                        echo "<input type=\"radio\" name=\"sort_order\" value=\"ascending\" $ascending_sort_order_selected>";
                        $form->displayLabel("ascending");
                        $descending_sort_order_selected=($sort_order=="descending")?"checked":"";
                        echo "<input type=\"radio\" name=\"sort_order\" value=\"descending\" $descending_sort_order_selected >";
                        $form->displayLabel("descending");        
                        echo "</td>";
                        echo "<td align=\"right\">";
                                echo $form->generateInputTag("submit",array("accesskey"=>"3","name"=>"show","value"=>"Show"));
                        echo "</td>";
                echo "</tr>";
        echo "</table>";
        echo "</form><br/>";
        }

function array_values_duplicate($array)
        {
        // counts how many times a value in an array is repeated
        $count_arrays=array_count_values($array);
        foreach($count_arrays as $key=>$value)
                {
                // if values are duplicated then return true
                if($key != "" && $value > 1)
                        {
                        return true;
                        }
                }
        return false;
        }

function array_duplicate($main_array,$fields)
        {
        $bool=true;
        $count=count($main_array[$fields[0]]);
        for($i=0;$i<$count;$i++)
                {
                for($j=$i+1;$j<$count;$j++)
                        {
                        foreach($fields as $key=>$value)
                                {
                                $bool=($bool && $main_array[$value][$i]==$main_array[$value][$j] && $main_array[$value][$i]!="");
                                }
                        //$bool=($bool && $i!=$j);
                        if($bool)
                                return $bool;
                        else
                                $bool=true;
                        }
                }
        return false;
        }

function trimFormValues(&$mainArray,$field)
        {
        foreach($field as $key=>$value)
                {
                if(is_array($mainArray[$value]))
                        {
                        foreach($mainArray[$value] as $key1=>$value1)
                                {
                                $mainArray[$value][$key1]=trim($value1);
                                }
                        }
                else
                        $mainArray[$value]=trim($mainArray[$value]);
                }
        }

?>
